#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: __init__.py.py
@time: 2020/8/10 6:25 下午
@desc:
'''
from sanic import Sanic
from sanic.response import json
from sanic.exceptions import RequestTimeout, NotFound
import traceback
from .exception import CustomException
from  sanic.handlers import ErrorHandler
from .g import G
from conf import conf
from .my_log import logger
import time

class CustomHandler(ErrorHandler):

    def default(self, request, exception):
        logger.error(traceback.format_exc())
        if isinstance(exception, CustomException):
            data = {
                'info': exception.message,
                'code': exception.code,
            }
            if exception.error:
                data.update({'error': exception.error})
            return json(data, status=exception.status_code)
        else:
            return json({'code':400,'info':'系统错误'})


def parse_request_agent(user_agent):
    try:
        from ua_parser import user_agent_parser
        parsed_string = user_agent_parser.Parse(user_agent)
        device = parsed_string.get('user_agent').get('family')
        os = parsed_string.get('os').get('family')
    except:
        if 'Android' in user_agent:
            os = 'Android'
        elif 'iPhone' in user_agent or 'iphone' in user_agent:
            os = 'iPhone'
        elif 'Mac' in user_agent:
            os='Mac'
        else:
            os = 'Win'
        if 'MicroMessenger' in user_agent:
            device = 'weixin'
        elif 'AlipayClient' in user_agent:
            device = 'alipay'
        else:
            device = 'web'
    return os,device

import socket
def get_server_ip():
    '''
    本机ip
    :return:
    '''
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

def get_client_ip(req):
    ip = req.headers.get("X-Forwarded-For", '')
    if ip is None or ip == '':
        ip = req.headers.get("X-Real-IP", '')
    if ip is None or ip == '':
        ip = req.headers.get("X-Client-Ip", '')
    if not ip:
        ip = req.ip
    return ip.split(',')[0]

from .utils import set_auth_cookies,get_auth_cookies
appid = conf.app.app_name
template = conf.app.app_static

_setting = {
    'REQUEST_BUFFER_QUEUE_SIZE':512,
    'KEEP_ALIVE':False,
    'KEEP_ALIVE_TIMEOUT':5,
    'ACCESS_LOG':True,
    'API_VERSION':'1.0.0',
    'API_TERMS_OF_SERVICE':'Use with Sanic!'
}

app = Sanic(__name__)
app.config.update(_setting)
app.name = appid

@app.listener('before_server_start')
async def before_server_start(app, loop):
    app.set_auth_cookies = set_auth_cookies
    app.get_auth_cookies = get_auth_cookies
    #mongo客户端
    #app.client = G.mongo_client
    logger.info('before start app')

@app.listener('after_server_start')
async def after_server_started(app,loop):
    logger.info('after start app')

@app.middleware('request')
async def before_request(request):
    request.headers['start_time']=time.perf_counter()

#资源释放
@app.middleware('response')
async def after_request(request, response):
    print(type(request))
    logger.debug(request.path + f'-->timer:{int((time.perf_counter()-request.headers["start_time"])*1000)}')
    G.getInstance().clear()
    if hasattr(response,'headers'):
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "x-requested-with"
        response.headers["Access-Control-Allow-Methods"] = 'POST, GET, OPTIONS,DELETE'
        return response

@app.exception(RequestTimeout)
def timeout(request, exception):
    return json({'info': 'Request Timeout'}, 408)


@app.exception(NotFound)
def notfound(request, exception):
    return json({'info': 'Requested URL {} not found'.format(request.url)}, 404)

